<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PageQuery } from '#/api/common';

import type { Device } from '#/api/iot/device/group/model';

import { onMounted, ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';

import { $t } from '@vben/locales';

import { getVxePopupContainer } from '@vben/utils';

import { useDebounceFn } from '@vueuse/core';

import { message, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { unbindDevice } from '#/api/iot/device/group';
import { devicetGroupList } from '#/api/iot/device/manage';
import { getProductList } from '#/api/iot/product';

import { router } from '#/router';

import bindDeviceDrawer from './bind-device-drawer.vue';
/**
 * querySchema: 搜索区域的数据
 * columns: table区域的数据
 */
import { columns, querySchema } from './data';
// 左侧树组件
import DeptTree from './dept-tree.vue';

/**
 * 导入
 */

async function batchUnbindDevices() {
  const deviceGroupId = sessionStorage.getItem('selectDeptId') || '';
  const deviceIds = tableApi.grid
    .getCheckboxRecords()
    .map((item) => item.id)
    .join(',');
  await unbindDevice({
    deviceGroupId,
    deviceIds,
  });
  tableApi.reload();
}

// 左边部门用
const selectDeptId = ref<string[]>([]);

const formOptions: VbenFormProps = {
  schema: querySchema(),
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  handleReset: async () => {
    // selectDeptId.value = [];

    const { formApi, reload } = tableApi;
    await formApi.resetForm();
    const formValues = formApi.form.values;
    formApi.setLatestSubmissionValues(formValues);
    await reload(formValues);
  },
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
    checkMethod: ({ row }) => row?.userId !== 1,
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  toolbarConfig: {
    custom: false,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 部门树选择处理
        if (selectDeptId.value.length === 1) {
          formValues.groupId = selectDeptId.value[0];
          sessionStorage.setItem('selectDeptId', formValues.groupId);
        } else {
          Reflect.deleteProperty(formValues, 'deptId');
        }

        return await devicetGroupList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  headerCellConfig: {
    height: 44,
  },
  cellConfig: {
    height: 48,
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'device-group-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [BindDeviceDrawer, bindDeviceDrawerApi] = useVbenDrawer({
  connectedComponent: bindDeviceDrawer,
});

const popVisible = ref<boolean>(false);

const handleVisibleChange = (bool: boolean) => {
  const deviceIds = tableApi.grid
    .getCheckboxRecords()
    .map((item) => item.id)
    .join(',');
  if (!bool) {
    popVisible.value = false;
    return;
  }
  if (deviceIds.length <= 0) {
    message.warning('请先选择设备');
  } else {
    popVisible.value = true;
  }
};

function handleDetail(row: Device) {
  router.push(`/device/detail/${row.id}`);
}

async function handleDelete(row: Device) {
  const deviceGroupId = sessionStorage.getItem('selectDeptId') || undefined;
  await unbindDevice({
    deviceGroupId,
    deviceIds: row.id,
  });
  tableApi.query();
}

function batchBindDevices() {
  const deviceGroupId = sessionStorage.getItem('selectDeptId') || undefined;
  if (!deviceGroupId) {
    message.warning('请先选择分组');
    return;
  }
  bindDeviceDrawerApi.open();
}

const initFormData = async (val?: string) => {
  const params: PageQuery = {};
  if (val) {
    params.productName = val;
  }
  const res = await getProductList(params);
  const options = res.rows || [];

  // 产品信息
  tableApi.formApi.updateSchema([
    {
      componentProps: {
        fieldNames: { label: 'productName', value: 'id' },
        options,
        showSearch: true,
        filterOption: false,
        onSearch: useDebounceFn(async (val: string) => {
          initFormData(val);
        }, 300),
      },
      fieldName: 'productId',
    },
  ]);
};

onMounted(() => {
  initFormData();
  sessionStorage.clear();
});
</script>

<template>
  <Page :auto-content-height="true">
    <div class="flex h-full gap-[8px]">
      <DeptTree
        v-model:select-dept-id="selectDeptId"
        class="w-[280px]"
        @reload="() => tableApi.reload()"
        @select="() => tableApi.reload()"
      />
      <BasicTable class="flex-1 overflow-hidden" table-title="">
        <template #toolbar-tools>
          <Space>
            <a-button v-access:code="['iot:deviceGroup:bind']" @click="batchBindDevices">
              批量绑定设备
            </a-button>
            <Popconfirm
              :open="popVisible"
              @open-change="handleVisibleChange"
              :get-popup-container="getVxePopupContainer"
              placement="left"
              title="是否要解绑选择的设备？"
              @confirm="batchUnbindDevices"
            >
              <a-button v-access:code="['iot:deviceGroup:unbind']" @click.stop="">
                批量解绑设备
              </a-button>
            </Popconfirm>
          </Space>
        </template>
        <template #action="{ row }">
          <template v-if="row.userId !== 1">
            <Space>
              <ghost-button
                v-access:code="['iot:deviceGroup:query']"
                @click.stop="handleDetail(row)"
              >
                设备详情
              </ghost-button>
              <Popconfirm
                :get-popup-container="getVxePopupContainer"
                placement="left"
                title="是否要解绑该设备？"
                @confirm="handleDelete(row)"
              >
                <ghost-button danger v-access:code="['iot:deviceGroup:unbind']" @click.stop="">
                  解绑设备
                </ghost-button>
              </Popconfirm>
            </Space>
          </template>
        </template>
      </BasicTable>
    </div>
    <BindDeviceDrawer @reload="tableApi.query()" />
  </Page>
</template>
